package cn.lee.share.http;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import cn.lee.TomcatConstants;
import cn.lee.share.pojo.Directory;
import cn.lee.share.utils.FreemarkerUtils;
import cn.lee.share.utils.VelocityUtils;
import freemarker.template.TemplateException;

public class DynamicProcesser {
    public static final int BUFFER_SIZE = 2048;
    
    /**
     * this method is to retrieve file list
     * @param uri
     * @return
     */
     Directory getFilelist(String uri){
        Directory d = new Directory();
        File file = new File(uri);
        if(file.exists()){
            int last = uri.lastIndexOf(TomcatConstants.URI_SEPARATOR);
            if( uri.lastIndexOf(TomcatConstants.URI_SEPARATOR) == uri.length()-1){
                last = uri.lastIndexOf(TomcatConstants.URI_SEPARATOR, last-1);
            }
            String parentFolder = uri.substring(0, (last+1) );
            d.setParentFolder(parentFolder);
            
            if(uri.lastIndexOf(TomcatConstants.URI_SEPARATOR) != (uri.length()-1) ){
                uri = uri + TomcatConstants.URI_SEPARATOR;
            }
            d.setUri(uri);
            
            String[] files = file.list();
            d.setFileNames(files);
        }
        return d;
    }
    
     private void setHeader(Response response){
         response.setContentType("text/html;charset=utf-8");
     }
     
    public void process(Request request, Response response) throws IOException{
        
        String uri = request.getUri();
        Directory directory = getFilelist(uri);
        
        if(!directory.exists()){
            StaticResourceProcesser staticResourceProcesser = new StaticResourceProcesser();
            //mean root folder /
            staticResourceProcesser.setFolder(TomcatConstants.URI_SEPARATOR);
            staticResourceProcesser.process(request, response);
            return;
        }
        setHeader(response);
        Map data = new HashMap();
        data.put("data", directory);
        Writer out = response.getWriter();
        try {
//            FreemarkerUtils.runTemplate(header, "responseHeader.html", out);
//            FreemarkerUtils.runTemplate(data, "listFolder.html", out);
            VelocityUtils.runTemplate(data, "listFolder.html", out);
        } catch (TemplateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
